/**
 * 查询smtp服务器
 * @returns {boolean} 已设置 则返回true
 */
function querySmtp(){
    var id = $('.config-mail').attr('data-id');
    var flag = false;
    if(!id){
        var id = $('#userid').val();
        $.ajax({
            type:"POST",
            url: "/cfginfo",
            async: false,
            data: {id:id},
            success: function(result){
                if(result != 'fail'){
                    if(result.length>0){
                        var info = result[0];
                        $('.config-mail').attr('data-id',info.mail_id);
                        $('#smtp').val(info.host);
                        $('input[name="ssl"][value="'+info.secure+'"]').attr('checked',true);
                        $('#port').val(info.port);
                        $('#account').val(info.user);
                        $('#pass').val(info.pass);
                        $('#interval').val(info.intervals);
                        flag = true;
                    }

                }else{
                    window.success('查询SMTP服务器失败！');
                }
            },
            error: function(){ window.error('请求异常！');}
        });
    }else{
        flag = true;
    }
    return flag;
}
KindEditor.ready(function(K) {
    var params = {
        'param1':{name:'参数1'},'param2':{name:'参数2'},'param3':{name:'参数3'},'param4':{name:'参数4'},
        'param5':{name:'参数5'},'param6':{name:'参数6'},'param7':{name:'参数7'},'param8':{name:'参数8'},
        'param9':{name:'参数9'},'param10':{name:'参数10'}
    }
    K.each(params,function(pluginName, pluginData){
        var lang = {};
        lang[pluginName] = pluginData.name;
        KindEditor.lang( lang );
        KindEditor.plugin(pluginName, function(K) {
            var editor = this;
            // 点击图标时执行
            editor.clickToolbar(pluginName, function() {
                var num = pluginName.replace('param','');
                var param = '#'+num+'#';
                editor.insertHtml(param);
            });
        });
    })
    K.each({
        'plug-align' : {
            name : '对齐方式',
            method : {
                'justifyleft' : '左对齐',
                'justifycenter' : '居中对齐',
                'justifyright' : '右对齐'
            }
        },
        'plug-order' : {
            name : '编号',
            method : {
                'insertorderedlist' : '数字编号',
                'insertunorderedlist' : '项目编号'
            }
        },
        'plug-indent' : {
            name : '缩进',
            method : {
                'indent' : '向右缩进',
                'outdent' : '向左缩进'
            }
        }
    },function( pluginName, pluginData ){
        var lang = {};
        lang[pluginName] = pluginData.name;
        KindEditor.lang( lang );
        KindEditor.plugin( pluginName, function(K) {
            var self = this;
            self.clickToolbar( pluginName, function() {
                var menu = self.createMenu({
                        name : pluginName,
                        width : pluginData.width || 100
                    });
                K.each( pluginData.method, function( i, v ){
                    menu.addItem({
                        title : v,
                        checked : false,
                        iconClass : pluginName+'-'+i,
                        click : function() {
                            self.exec(i).hideMenu();
                        }
                    });
                })
            });
        });
    });
    var paramarr = [];
    for(var i=1;i<=9;i++){paramarr.push('param'+i);}
    var editor = K.create('#contentqq', {
            themeType : 'qq',
            items : [
                'source','bold','italic','underline','fontname','fontsize','forecolor','hilitecolor','image','plug-align','plug-order','plug-indent','link','fullscreen'
            ].concat(paramarr)
        });

    $('#send').click(function(){
        //邮件信息判断之前 判断是否已设置好邮件服务器
        if(!querySmtp()){
            window.error('尚未设置邮件服务器！');
            $('.config-mail').animate({top:'70px'},'slow');
            return;
        }
        var data = {};
        data.subject = $('#subject').val();
        if(!data.subject){
            window.error('发送主题不能为空！');
            return;
        }
        var files = [];
        $('#receiver ul li').each(function(){
            files.push($(this).find('span').html());
        });
        if(!files.length){
            window.error('发送对象不能为空！');
            return;
        }
        data.receiver = files.join(',');
        data.content = editor.html();
        if(!data.content){
            window.error('正文不能为空！');
            return;
        }

        //建立状态通讯socket连接
       var socket = io.connect('',{'force new connection':true});//强制建立新连接
        //收到server的返回身份标示
        socket.on('system',function(ID){
            data.ID = ID;
            var $obj = $('#sub input[type="button"]');
            $.ajax({
                type:"POST",
                url: "/send",
                data: data,
                beforeSend: function(){$obj.attr("disabled",true);},
                complete: function(){},
                success: function(result){
                    var d = null;
                    var success = fail = 0;
                    if (result == 'start') {
                        d = window.success('提交成功，请等待返回最后结果！');
                    }else if(result == 'nosession'){
                        window.location.href = '/login';
                    }else{
                        d = window.error('邮件服务器获取失败！');
                        $obj.attr("disabled",false);
                        socket.disconnect();
                        return;
                    }
                    //监听message事件，邮件已发送封数
                    socket.on('success',function(json){
                        window.success('<div class="success">'+json.time+' '+json.to+'</div>');
                        socket.emit('rpt',{success:++success,fail:fail});
                    });
                    socket.on('fail',function(json){
                        window.success('<div class="fail">'+json.time+' '+json.to+'</div>');
                        socket.emit('rpt',{success:success,fail:++fail});
                    });
                    //监听邮件发送完成
                    socket.on('finish',function(result){
                        $obj.attr("disabled",false);
                        window.success('本次发送完成！邮件总数：'+(success+fail)+'!<br>其中成功'+success+',失败'+fail);
                        socket.disconnect();
                    });
                    socket.emit('rpt',{success:0,fail:0});
                },
                error: function(){window.error('请求异常！'); $obj.attr("disabled",false);socket.disconnect();}
            })
        });

    })
		});

$(function () {
    var result = ['','单次请求文件数不超过10','不支持的文件类型','单次上传总大小2M'];
    'use strict';
    $('#fileupload').fileupload({
        url: '/upload',
        dataType: 'json',
        autoUpload: true,
        singleFileUploads:false,
        done: function (e, data) {
            data = data.result;
            if(data.result == '000'){
                $.each(data.files, function (index, file) {
                    $('#receiver ul').append('<li class="border-b"><em class="fright"></em><span class="ellipsis">'+file.name+'</span></li>');
                });
            }else{
                window.error(result[data.result-0]);
            }

        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress').show();
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
            if(progress == 100){
            	window.setTimeout(function(){
            		$('#progress').hide();
            	},1000);
            }
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');

    //删除文件
    $('.send-wrap').delegate('.remove','click',function(){
        var $obj = $(this);
        var name = $obj.siblings('span').html();
        $.ajax({
            type:"POST",
            url: "/remove",
            data: {name:name},
            beforeSend: function(){$obj.removeClass('remove').addClass('load');},
            complete: function(){$obj.removeClass('load').addClass('remove');},
            success: function(result){
                if(result == 'success'){
                    $obj.parent('li').remove();
                    window.success('删除成功！');
                }else{
                    window.success('删除失败！');
                }
            },
            error: function(){ window.error('请求异常！');}
        })
    }).delegate('li','mousemove',function(){
        $(this).css('background','#a6a6a6');
        $(this).find('em').addClass('remove');
    }).delegate('li','mouseout',function(){
        $(this).css('background','');
        $(this).find('em').removeClass('remove');
    });

    //弹出隐藏邮件服务器设置框
    $('.config').click(function(){
        var $cfg = $('.config-mail');
        if(!$cfg.is(':animated')){
            if($cfg.position().top<0){
                $cfg.animate({top:'70px'},'slow');
                querySmtp();
            }else{
                $cfg.animate({top:'-420px'},'slow');
            }

        }

    });

    //设置邮件服务器
    $('.bt-cfg').click(function(){
        var $obj = $(this);
        var id = $('#userid').val();
        var smtp = $('#smtp').val();
        var ssl = $('input[name="ssl"]:checked').val();
        var port = $('#port').val();
        var account = $('#account').val();
        var pass = $('#pass').val();
        var interval = $('#interval').val();
        var data =  {id:id,smtp:smtp,ssl:ssl,port:port,account:account,pass:pass,interval:interval};
        if($('.config-mail').attr('data-id')){//新增或者修改
            data.cfgid = $('.config-mail').attr('data-id');
        }
        $.ajax({
            type:"POST",
            url: "/cfg",
            data: data,
            beforeSend: function(){$obj.attr('disabled',true).val('操作中。。');},
            complete: function(){$obj.attr('disabled',false).val('设置');;},
            success: function(result){
                if(result != 'fail'){
                    $('.config-mail').attr('data-id',result.insertId);
                    window.success('设置成功！');
                }else{
                    window.success('设置失败！');
                }
            },
            error: function(){ window.error('请求异常！');}
        });
    });

    $('.param').delegate('[class^="param"]','click',function(e){
        var target = getEtarget();
        var classname = $(target).attr('class');
        var num = classname.replace('param','');
        var param = '#'+num+'#';
        var subject = document.getElementById('subject');
        var pos = getPosition(subject);
        var ov = subject.value;
        var len = ov.length;
        subject.value = ov.substr(0,pos)+param+ov.substr(pos);//插入参数
        setCaretPosition(subject,pos+param.length);//调整光标位置
    })

    /**
     * 控制参数选择框的显示及隐藏
     */
    $.each([$('#subject'),$('.param')],function(){
        this.bind('focus click',function(e){
            $('.param').show(600);
            var event = e || window.event;
            e.stopPropagation();
        });
    });
    $(document).click(function(e){
        $('.param').hide(600);
    });
});